<template>
  <div class="app-container">
    <div id="printBox">
      <div
        style="margin-bottom: 20px"
        v-for="item in printData"
        :key="item?.id"
      >
        <div
          :id="`printId_${item?.id || ''}`"
          style="width: 350px; height: 350px"
        >
          <!--&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-->
          <div
            style="
              font-size: 20px;
              display: flex;
              justify-content: center;
              margin-bottom: 20px;
              margin-top: 20px;
            "
          >
            <canvas :id="`barcode_${item?.id || ''}`"></canvas>
          </div>
          <div
            style="
              font-size: 12px;
              font-weight: 600;
              word-break: break-all;
              width: 350px;
              margin-bottom: 10px;
              /* background-color: red; */
              /* border: 1px solid #000; */
            "
          >
            <span style="font-size: 18px; font-weight: 100"
              ><text style="font-size: 20px; font-weight: 600">{{
                item?.materialBarcode || ""
              }}</text></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 350px">
            <span style="font-size: 18px; font-weight: 100; font-weight: 600"
              >产品编号：<text
                style="font-size: 19px; font-weight: 600; margin-right: 20px"
                >{{ item?.materialCode || "" }}</text
              ></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 350px">
            <br />
            <span style="font-size: 18px; font-weight: 100; font-weight: 600"
              >产品名称：<text style="font-size: 16px; font-weight: 600">{{
                item?.materialName || ""
              }}</text></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 350px">
            <br />
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >图号：<text style="font-size: 20px; font-weight: 600">{{
                item?.figureNumber || ""
              }}</text></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: 0px; width: 350px">
            <br /><span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 10px;
                font-weight: 600;
              "
              >生产批次：<text
                style="font-size: 19px; font-weight: 600; margin-right: 10px"
                >{{ item?.materialBatch || "" }}</text
              ></span
            >
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >数量：<text style="font-size: 19px; font-weight: 600"
                >{{ item?.capacityQuantity || "" }}
                {{ filterUnit(item?.quantityUnit) || "" }}</text
              >
            </span>
          </div>
          <div style="height: 14px">&nbsp;</div>
          <div style="font-size: 13px; width: 350px; margin-bottom: 4px">
            <span
              style="
                font-size: 13px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >打印时间：<text>{{ item?.printTime || "" }}</text></span
            >
            <span
              style="
                font-size: 13px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >打印人：<text
                >{{ route.query?.printername || "" }}&nbsp;</text
              ></span
            >
          </div>
          <div style="height: 3px"></div>
          <div style="font-size: 13px; width: 400px; display: flex">
            <span style="flex: 1.3; font-size: 13px; font-weight: 600">
              操作者1：
              <text>{{
                item?.createdUserName || route.query?.printername
              }}</text>
            </span>
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 13px;
                margin-right: 20px;
                font-weight: 600;
              "
              >操作者2：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 13px;
                margin-right: 20px;
                font-weight: 600;
              "
              >检&nbsp;查：&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
          </div>
          <div
            style="
              font-size: 17px;
              margin-bottom: 0px;
              width: 300px;
              font-weight: 600;
            "
          ></div>
        </div>
        <div style="margin-top: 10px">
          <div style="text-align: center" v-show="printData.length > 0">
            <el-button size="small" @click="getPrintData()">打印条码</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { getLodop } from "@/utils/LodopFuncs";
import { useRoute, useRouter } from "vue-router";
import QRCode from "qrcode";
import { useDictStoreHook } from "@/store/modules/dictionary";
import printJS from "print-js";
// import { uni } from "@/utils/uni.webview.1.5.4.js";
// 1、name每个页面不能重复，2、路由在router.ts中添加，3、添加至路由白名单（permission.ts中whiteList）
defineOptions({
  name: "IframePrintSchedule",
  inheritAttrs: false,
});

// 打印模板全用div和span等原生html书写（确保打印格式不变）
// 样式全用行内style书写（确保样式生效）

const route = useRoute();
const useDictStore = useDictStoreHook();

// 打印数据，数组形式
const printData = ref<any[]>([]);

let router = useRouter();

// 监听路由变化，检测是否开始打印
watch(
  () => router.currentRoute.value,
  (newValue) => {
    console.log("watch", JSON.stringify(newValue));
    if (newValue.query?.id) {
      getPrintData();
    }
  },
  { immediate: true, deep: true }
);

// 获取打印数据
async function getPrintData() {
  let data1: any = [];
  // 单条打印
  if (route.query?.type == "single") {
    const { data } = await request({
      url: `/mes/mesturnovercard/get/${route.query.id}`,
      method: "get",
      data: {},
    })
      .finally(() => {})
      .catch((e) => {
        uni.postMessage({
          data: {
            message: "单条打印失败" + e,
            code: 0,
            // id: route.query.id,
            printer: route.query?.printer ?? "",
          },
        });
      });
    data1 = [data];
  } else {
    // 批量打印
    const { data } = await request({
      url: `/mes/mesplanworkingform/printTurnoverCard`,
      method: "post",
      data: {
        id: route.query.id,
        capacityQuantity: route.query.capacityQuantity,
        printNum: route.query.printNum,
      },
    })
      .finally(() => {})
      .catch((e) => {
        uni.postMessage({
          data: {
            message: "批量打印失败" + e,
            code: 0,
            // id: route.query.id,
            printer: route.query?.printer ?? "",
          },
        });
      });
    data1 = data;
  }

  //单张打印
  // const data1 = data;
  data1.forEach((item) => {
    item.printTime = new Date().toLocaleString();
  });
  printData.value = data1;
  //   const printTime = new Date().toLocaleString();
  nextTick(() => {
    printData.value?.map(async (e) => {
      const qrCodeId = `barcode_${e?.id || ""}`;
      const qrCodeElement = document.getElementById(qrCodeId);
      if (qrCodeElement) {
        try {
          await QRCode.toCanvas(qrCodeElement, e?.materialBarcode || "", {
            width: 100, // 可以根据需要调整二维码的大小
            margin: 1, // 可以根据需要调整二维码的边距
          });
        } catch (err) {
          console.error("Error generating QR code:", err);
        }
      }
    });
  });
  setTimeout(() => {
    // let LODOP = getLodop();
    // LODOP.PRINT_INIT(`周转卡标签打印-${route.query.id}`);
    // // LODOP.SET_LICENSES(
    // //   defaultSettings.printCompany,
    // //   defaultSettings.printLicenses,
    // //   "",
    // //   ""
    // // );
    // printData.value?.map((e) => {
    //   printFun(e, LODOP);
    // });
    // // console.log("打印机列表", LODOP.Printers.list);
    // LODOP.SET_PRINTER_INDEX(route.query?.printer ?? "");
    // // LODOP.PRINT(); // 打印
    // LODOP.PREVIEW(); // 预览
    printJS({
      printable: "printBox", // id
      type: "html", //打印类型
      scanStyles: false,
      style:
        "@media print { @page { margin: 0mm; } body { margin: 0;display: flex;justify-content: center; } }",
    });
    if (uni) {
      uni.postMessage({
        data: {
          message: "已成功进入打印队列，请稍后",
          code: 200,
          // id: route.query.id,
          printer: route.query?.printer ?? "",
        },
      });
    }

    // 打印结束调用
    insertOperateLog(route.query.id, route.query?.printer ?? "");
  }, 500);
}

function printFun(pitem: any, LODOP: any) {
  LODOP.SET_PRINT_PAGESIZE(1, "100mm", "100mm", ""); // 设置纸张类型（方向、宽度、高度、纸张类型名称）
  //LODOP.ADD_PRINT_RECT(0, 5, 310, 220, 0, 1); //边框设置：上、左、宽、高、线条：0实线 1虚线
  //LODOP.SET_PRINT_STYLE("FontSize", 7.5);
  LODOP.SET_PRINT_STYLE("FontName", "微软雅黑"); // 需要服务端机器安装同样字体，才能生效
  LODOP.ADD_PRINT_HTM(
    "38mm",
    "4mm",
    "100mm",
    "100mm",
    document.getElementById(`printId_${pitem?.id || ""}`)?.innerHTML
  );
  LODOP.ADD_PRINT_BARCODE(
    "4mm",
    "34mm",
    "40mm",
    "40mm",
    "QRCode",
    pitem?.materialBarcode || ""
  );
  LODOP.NEWPAGE(); //另起一页
}
//打印日志信息
const operateLog = ref({
  logLevel: "INFO",
  applicationName: "jcfk-mes",
  modular: "周转条码标签打印开始结束",
  businessType: "打印",
  info: "",
});
//结束打印
async function insertOperateLog(id: any, name: any) {
  operateLog.value.info = id + "," + name;
  await request({
    method: "POST",
    url: "/system/sysOperateLog/insert",
    data: operateLog.value,
  }).catch((e) => {});
}

onMounted(async () => {
  // 数据字典表获取
  // await useDictStore.getDictionaryList();
  // 获取打印数据
  // getPrintData();
});

const unitList = [
  {
    value: "1",
    label: "个",
  },
  {
    value: "2",
    label: "件",
  },
  {
    value: "3",
    label: "包",
  },
  {
    value: "4",
    label: "千克",
  },
  {
    value: "5",
    label: "PCS",
  },
  {
    value: "6",
    label: "张",
  },
  {
    value: "7",
    label: "卷",
  },
];
function filterUnit(param: string) {
  return unitList.find((e) => e.value == param)?.label || "";
}
</script>

<style lang="scss" scoped>
.app-container {
  height: inherit;
  overflow: scroll;
}
</style>
